package com.zy.cat.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkGoodsPromotionUrlGenerateResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkGoodsSearchResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkMemberAuthorityQueryResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkRpPromUrlGenerateResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkThemePromUrlGenerateResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkRpPromUrlGenerateResponse.RpPromotionUrlGenerateResponseUrlListItem;
import com.zy.cat.entity.pdd.PddLotteryUrl;
import com.zy.cat.entity.pdd.PddMallConvert;
import com.zy.cat.entity.pdd.PddResourceUrl;
import com.zy.cat.entity.pdd.PddShopConvert;
import com.zy.cat.entity.pdd.PddShops;
import com.zy.cat.entity.pdd.PddShopsDetail;
import com.zy.cat.entity.pdd.PddTopShops;
import com.zy.cat.entity.pdd.PddZtConvert;
import com.zy.cat.entity.resp.Pages;
import com.zy.cat.entity.resp.ResultPage;
import com.zy.cat.service.PddShopsService;
import com.zy.cat.common.annotation.RedisSingle;
import com.zy.cat.common.config.Configs;
import com.zy.cat.common.utils.PDDAPI;
import com.zy.cat.common.utils.TJKUtils;
import com.zy.cat.service.CacheService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class PddShopsServiceImpl implements PddShopsService {

	@Autowired
	CacheService cacheService;

	@Autowired
	Configs configs;

	@Autowired
	@Qualifier("redis11")
	RedisTemplate<String, Integer> redis11;

	@Override
	public List<Map<String, Object>> pddCatList(int rtype, Long parent_cat_id) {
		parent_cat_id = parent_cat_id == null ? 0l : parent_cat_id;
		return cacheService.getPddOpts(parent_cat_id.intValue());
	}

	@Override
	public ResultPage<PddShops> pddList(String pid,Integer rtype, String query, Integer sortType, Long cat_id, Long opt_id,
			Integer withCoupon, Pages pages) {
		cat_id = cat_id == null ? 0l : cat_id;
		opt_id = opt_id == null ? 0l : opt_id;
		sortType = sortType == null ? 0 : sortType;
		withCoupon = withCoupon == null ? 0 : withCoupon;
		query = query == null ? "" : query;
		pid=pid==null?"":pid;
		
		ResultPage<PddShops> result = null;
		List<PddShops> rlist = new ArrayList<PddShops>();

		String key = DigestUtils.md5DigestAsHex((pid+""+pages.getPageNum() + "" + pages.getPageSize() + "" + sortType + ""
				+ cat_id + "" + opt_id + "" + query + "" + withCoupon).getBytes());
		PddDdkGoodsSearchResponse shopList = cacheService.getPddShopList(pid,key, query, pages.getPageNum(),
				pages.getPageSize(), sortType, cat_id, opt_id, withCoupon == 1);

		if (shopList != null && shopList.getGoodsSearchResponse() != null
				&& shopList.getGoodsSearchResponse().getTotalCount() > 0) {
			shopList.getGoodsSearchResponse().getGoodsList().forEach(shop -> {
				PddShops rshop = new PddShops(shop);
				
				//屏蔽用户比价商品 2020-08-18
				if(rshop.getPredictPromotionRate()!=null&&rshop.getPredictPromotionRate()<=0) {
					return;
				}

				if (rshop.getPromotion_rate() > 0) {

					double rate = 0.4;
					long dfcode = 0;
					long pfcode = 0;
					if (rshop.isHas_coupon()) {
						long dfinal_pricce = rshop.getMin_normal_price() - rshop.getCoupon_discount();
						long pfinal_pricce = rshop.getMin_group_price() - rshop.getCoupon_discount();
						dfcode = (long) ((double) (rate * dfinal_pricce * rshop.getPromotion_rate() / 1000));
						pfcode = (long) ((double) (rate * pfinal_pricce * rshop.getPromotion_rate() / 1000));
					} else {
						dfcode = (long) ((double) (rate * rshop.getMin_normal_price() * rshop.getPromotion_rate()
								/ 1000));
						pfcode = (long) ((double) (rate * rshop.getMin_group_price() * rshop.getPromotion_rate()
								/ 1000));
					}
					log.info("-单买价--->" + rshop.getMin_normal_price());
					log.info("-拼团价--->" + rshop.getMin_group_price());
					log.info("-优惠券--->" + rshop.getCoupon_discount());
					log.info("-佣金比例--->" + rshop.getPromotion_rate());
					log.info("-平台比例--->" + rate);
					log.info("-单买返利--->" + dfcode);
					log.info("-拼团返利--->" + pfcode);
					log.info("----------------------------------->");

					rshop.setPfcode(pfcode * 2);
					rshop.setDfcode(dfcode);
					rlist.add(rshop);
				}

			});
			result = new ResultPage<PddShops>(pages.getPageNum(), pages.getPageSize(),
					shopList.getGoodsSearchResponse().getTotalCount(), rlist);
		}
		return result;
	}

	@Override
	public PddShopConvert pddShopConvert(int ctype, Integer rtype, String param, Long sid, Integer dtype) {
		PddShopConvert result = null;
		PddDdkGoodsPromotionUrlGenerateResponse resp = null;
		boolean weappWebview = true, WeApp = true, webo = true;
		resp = PDDAPI.getInstance(1, ctype).getShopConvert(sid, true, dtype == 1, param, weappWebview, WeApp, webo);
		if (resp != null && resp.getGoodsPromotionUrlGenerateResponse() != null
				&& !resp.getGoodsPromotionUrlGenerateResponse().getGoodsPromotionUrlList().isEmpty()) {
			result = new PddShopConvert(resp.getGoodsPromotionUrlGenerateResponse().getGoodsPromotionUrlList().get(0));
		}
		return result;
	}

	@Override
	public PddShopsDetail pddShopInfo(Integer rtype, Long sid) {
		PddShopsDetail result = null;
		String resultJson = cacheService.getPddShopInfo(sid);
		if (JSONObject.isValid(resultJson)) {
			result = JSON.parseObject(resultJson, PddShopsDetail.class);
		}
		if (result == null) {
			log.error("-拼多多无此商品--{}>", sid);
			return null;
		}
		if (StringUtils.isNotBlank(result.getCouponStartTime())) {
			String couponStartTime = TJKUtils.unix2LocalDateTime(Long.parseLong(result.getCouponStartTime()) * 1000l,
					"yyyy-MM-dd");
			result.setCouponStartTime(couponStartTime);
		}
		if (StringUtils.isNotBlank(result.getCouponEndTime())) {
			String couponEndTime = TJKUtils.unix2LocalDateTime(Long.parseLong(result.getCouponEndTime()) * 1000l,
					"yyyy-MM-dd");
			result.setCouponEndTime(couponEndTime);
		}
//		String couponStartTime=TJKUtils.unix2LocalDateTime(Long.parseLong(result.getCouponStartTime())*1000l, "yyyy-MM-dd");
//		String couponEndTime=TJKUtils.unix2LocalDateTime(Long.parseLong(result.getCouponEndTime())*1000l, "yyyy-MM-dd");
//		result.setCouponStartTime(couponStartTime);
//		result.setCouponEndTime(couponEndTime);
		return result;
	}

	@Override
	public List<PddZtConvert> pddZtConvert(int ctype, int rtype, String param, long tid) {
		PddDdkThemePromUrlGenerateResponse respResult = PDDAPI.getInstance(1, ctype).getThemeShop(param, tid);
		List<PddZtConvert> result = null;
		if (respResult != null && respResult.getThemePromotionUrlGenerateResponse() != null) {
			result = JSON.parseArray(JSON.toJSONString(respResult.getThemePromotionUrlGenerateResponse().getUrlList()),
					PddZtConvert.class);
		}
		return result;
	}

	@Override
	public PddResourceUrl getPddResourceUrl(String param, int rtype) {
		PddResourceUrl result = null;
		String resultJson = cacheService.getPddResourceUrl(param, rtype);
		if (JSONObject.isValid(resultJson)) {
			result = JSONObject.parseObject(resultJson, PddResourceUrl.class);
		}
		return result;
	}

	@Override
	public PddMallConvert getMallConvert(int ctype, int rtype, String param, long mid) {
		return cacheService.getPddMallConvert(ctype, rtype, param, mid);
	}

	@Override
	public List<PddTopShops> getTopShipList(String pid,int rtype, int page, int stype) {
		pid=pid==null?"":pid;
		List<PddTopShops> result = null;
		List<PddTopShops> resultList = null;
		String resultJson = cacheService.getPddTopShipList(pid,page, stype);

		/* 0.微信小程序 */
		double rate = 0.4;
		if (JSONArray.isValid(resultJson)) {
			resultList = JSONArray.parseArray(resultJson, PddTopShops.class);
			log.info("--->" + JSON.toJSONString(resultList));
			if (resultList != null && !resultList.isEmpty()) {
				result = resultList.stream().filter(new Predicate<PddTopShops>() {
					@Override
					public boolean test(PddTopShops t) {
						boolean preRate = t.getPredictPromotionRate() != null && t.getPredictPromotionRate() <= 0;
						boolean proRate = t.getPromotionRate()<=0;
						
						if (preRate||proRate) {
							return false;
						}
						return true;
					}
				}).map(shop -> {
					String couponStartTime = TJKUtils
							.unix2LocalDateTime(Long.parseLong(shop.getCouponStartTime()) * 1000l, "yyyy-MM-dd");
					String couponEndTime = TJKUtils.unix2LocalDateTime(Long.parseLong(shop.getCouponEndTime()) * 1000l,
							"yyyy-MM-dd");
					shop.setCouponStartTime(couponStartTime);
					shop.setCouponEndTime(couponEndTime);
					long dfcode = 0;
					long pfcode = 0;
//					if (shop.getHasCoupon()) {
					if (shop.getCouponRemainQuantity() > 0) {
						long dfinal_pricce = shop.getMinNormalPrice() - shop.getCouponDiscount();
						long pfinal_pricce = shop.getMinGroupPrice() - shop.getCouponDiscount();
						dfcode = (long) ((double) (rate * dfinal_pricce * shop.getPromotionRate() / 1000));
						pfcode = (long) ((double) (rate * pfinal_pricce * shop.getPromotionRate() / 1000));
					} else {
						dfcode = (long) ((double) (rate * shop.getMinNormalPrice() * shop.getPromotionRate() / 1000));
						pfcode = (long) ((double) (rate * shop.getMinGroupPrice() * shop.getPromotionRate() / 1000));
					}
					log.info("-单买价--->" + shop.getMinNormalPrice());
					log.info("-拼团价--->" + shop.getMinGroupPrice());
					log.info("-优惠券--->" + shop.getCouponDiscount());
					log.info("-佣金比例--->" + shop.getPromotionRate());
					log.info("-平台比例--->" + rate);
					log.info("-单买返利--->" + dfcode);
					log.info("-拼团返利--->" + pfcode);
					log.info("----------------------------------->");

					shop.setPfcode(pfcode * 2);
					shop.setDfcode(dfcode);
					return shop;
				}).collect(Collectors.toList());
			}

		}
		return result;
	}

	@Override
	public List<PddLotteryUrl> getPddLotteryUrl(String upid) {
		List<PddLotteryUrl> result = null;
		String resultJson = cacheService.getPddLotteryUrl(upid);
		if (JSONArray.isValid(resultJson)) {
			result = JSONArray.parseArray(resultJson, PddLotteryUrl.class);
		}
		return result;
	}

	@Override
	public List<PddShops> pddSearch(Integer rtype, String pid, String query, Integer stype) {
		int opt_id = 0;
		stype = stype == null ? 0 : stype;
		pid=pid==null?"":pid;
		int withCoupon = 1;

		List<PddShops> rlist = new ArrayList<PddShops>();
		String key = DigestUtils.md5DigestAsHex(
				(1 + "" + 100 + "" + stype + "" + 0 + "" + opt_id + "" + query + "" + withCoupon+ "" + pid).getBytes());
		PddDdkGoodsSearchResponse shopList = cacheService.getPddShopList(pid,key, query, 1, 100, stype, 0, opt_id,
				withCoupon == 1);

		if (shopList != null && shopList.getGoodsSearchResponse() != null
				&& shopList.getGoodsSearchResponse().getTotalCount() > 0) {
			shopList.getGoodsSearchResponse().getGoodsList().forEach(shop -> {
				PddShops rshop = new PddShops(shop);
				
				//屏蔽用户比价商品
				if(rshop.getPredictPromotionRate()!=null&&rshop.getPredictPromotionRate()<=0) {
					return;
				}

				if (rshop.getPromotion_rate() > 0) {
					double rate = 0.4;
					long dfcode = 0;
					long pfcode = 0;
					if (rshop.isHas_coupon()) {
						long dfinal_pricce = rshop.getMin_normal_price() - rshop.getCoupon_discount();
						long pfinal_pricce = rshop.getMin_group_price() - rshop.getCoupon_discount();
						dfcode = (long) ((double) (rate * dfinal_pricce * rshop.getPromotion_rate() / 1000));
						pfcode = (long) ((double) (rate * pfinal_pricce * rshop.getPromotion_rate() / 1000));
					} else {
						dfcode = (long) ((double) (rate * rshop.getMin_normal_price() * rshop.getPromotion_rate()
								/ 1000));
						pfcode = (long) ((double) (rate * rshop.getMin_group_price() * rshop.getPromotion_rate()
								/ 1000));
					}
					log.info("-单买价--->" + rshop.getMin_normal_price());
					log.info("-拼团价--->" + rshop.getMin_group_price());
					log.info("-优惠券--->" + rshop.getCoupon_discount());
					log.info("-佣金比例--->" + rshop.getPromotion_rate());
					log.info("-平台比例--->" + rate);
					log.info("-单买返利--->" + dfcode);
					log.info("-拼团返利--->" + pfcode);
					log.info("----------------------------------->");

					rshop.setPfcode(pfcode * 2);
					rshop.setDfcode(dfcode);
					rlist.add(rshop);
				}

			});

		}
		return rlist;
	}

	@Override
	@RedisSingle(key = "+#pid")
	public Object getPddAuth(int ctype, int rtype, String pid) {
		Map<String,String> resultMap=new HashMap<>();
		String key = "CAT_PDD_AUTH", hashKey = pid;
		if (redis11.opsForHash().hasKey(key, hashKey)) {
			return null;
		}

		PddDdkMemberAuthorityQueryResponse aresult = PDDAPI.getInstance(1, ctype).getBeiAnInfo(null, pid);
		if (aresult != null && aresult.getAuthorityQueryResponse() != null
				&& aresult.getAuthorityQueryResponse().getBind() == 1) {
			redis11.opsForHash().put(key, hashKey, TJKUtils.DateTime());
			return null;
		}
		PddDdkRpPromUrlGenerateResponse result = PDDAPI.getInstance(1, ctype).getBeiAnUrl(null, pid);
		//if (result != null && result.getRpPromotionUrlGenerateResponse() != null) {
			List<RpPromotionUrlGenerateResponseUrlListItem> list = result.getRpPromotionUrlGenerateResponse()
					.getUrlList();
			if (list != null && !list.isEmpty()) {
				for (RpPromotionUrlGenerateResponseUrlListItem action : list) {
					if (StringUtils.isNotBlank(action.getMobileUrl())) {
						resultMap.put("mobile_url", action.getMobileUrl());
						resultMap.put("url", action.getUrl());
						return resultMap;
					}
				}
			}
		//}
		return null;
	}

	/**
	 * 获取今日推荐商品信息
	 * @param rtype
	 * @param sid
	 * @return
	 */
	@Override
	public ResultPage<PddShops> pddTjShops(Integer rtype, Long sid,Integer sorttype,Integer withCoupon,Pages pages) {
		// TODO Auto-generated method stub
		withCoupon = withCoupon == null ? 0 : withCoupon;
		ResultPage<PddShops> result = null;
		List<PddShops> rlist = new ArrayList<PddShops>();

		String key = DigestUtils.md5DigestAsHex((sid+""+pages.getPageNum() + "" + pages.getPageSize() + "" + sorttype + ""
				+ withCoupon).getBytes());
		PddDdkGoodsSearchResponse shopList = cacheService.getPddShopTj(sid,key, pages.getPageNum(),
				pages.getPageSize(), sorttype,withCoupon == 1);

		if (shopList != null && shopList.getGoodsSearchResponse() != null
				&& shopList.getGoodsSearchResponse().getTotalCount() > 0) {
			shopList.getGoodsSearchResponse().getGoodsList().forEach(shop -> {
				PddShops rshop = new PddShops(shop);
				if (rshop.getPromotion_rate() > 0) {

					double rate = 0.4;
					long dfcode = 0;
					long pfcode = 0;
					if (rshop.isHas_coupon()) {
						long dfinal_pricce = rshop.getMin_normal_price() - rshop.getCoupon_discount();
						long pfinal_pricce = rshop.getMin_group_price() - rshop.getCoupon_discount();
						dfcode = (long) ((double) (rate * dfinal_pricce * rshop.getPromotion_rate() / 1000));
						pfcode = (long) ((double) (rate * pfinal_pricce * rshop.getPromotion_rate() / 1000));
					} else {
						dfcode = (long) ((double) (rate * rshop.getMin_normal_price() * rshop.getPromotion_rate()
								/ 1000));
						pfcode = (long) ((double) (rate * rshop.getMin_group_price() * rshop.getPromotion_rate()
								/ 1000));
					}
					log.info("-单买价--->" + rshop.getMin_normal_price());
					log.info("-拼团价--->" + rshop.getMin_group_price());
					log.info("-优惠券--->" + rshop.getCoupon_discount());
					log.info("-佣金比例--->" + rshop.getPromotion_rate());
					log.info("-平台比例--->" + rate);
					log.info("-单买返利--->" + dfcode);
					log.info("-拼团返利--->" + pfcode);
					log.info("----------------------------------->");

					rshop.setPfcode(pfcode * 2);
					rshop.setDfcode(dfcode);
					rlist.add(rshop);
				}

			});
			result = new ResultPage<PddShops>(pages.getPageNum(), pages.getPageSize(),
					shopList.getGoodsSearchResponse().getTotalCount(), rlist);
		}
		return result;
	}
}
